/**
 * Created by Allen on 2018/2/24.
 */
import {ChangeDetectorRef, Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {AppUrl} from '../../../app.url';
import {HttpClient} from '@angular/common/http';
import {NzMessageService} from 'ng-zorro-antd';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

@Component({
    selector: 'nz-demo-table-basic',
    template: `
        <nz-input [nzType]="'search'"
                  [nzPlaceHolder]="'类型'"
                  [(ngModel)]="_value" style="width: 200px;"
                  (nzOnSearch)="onSearch($event)">
        </nz-input>
        <!--<button nz-button [nzType]="'primary'" (click)="addDict()">
            <i class="anticon anticon-plus"></i><span>添加</span>
        </button>-->
        <button nz-button [nzType]="'primary'" (click)="showModal()">
            <i class="anticon anticon-plus"></i><span>添加</span>
        </button>
        <nz-modal [nzVisible]="isVisible" [nzTitle]="modalTitle" [nzContent]="modalContent" [nzFooter]="modalFooter"
                  (nzOnCancel)="handleCancel($event)">
            <ng-template #modalTitle>
                添加数据字典
            </ng-template>
            <ng-template #modalContent>
                <form nz-form [formGroup]="validateForm">
                    <div nz-form-item nz-row>
                        <div nz-form-label nz-col [nzSm]="6" [nzXs]="24">
                            <label for="type" nz-form-item-required>类型</label>
                        </div>
                        <div nz-form-control nz-col [nzSm]="14" [nzXs]="24" nzHasFeedback>
                            <nz-input [nzSize]="'large'" formControlName="type" [nzId]="'type'"></nz-input>
                            <div nz-form-explain
                                 *ngIf="getFormControl('type').dirty&&getFormControl('type').hasError('type')">请填写正确的类型!
                            </div>
                        </div>
                    </div>

                    <div nz-form-item nz-row>
                        <div nz-form-label nz-col [nzSm]="6" [nzXs]="24">
                            <label for="key" nz-form-item-required>标签</label>
                        </div>
                        <div nz-form-control nz-col [nzSm]="14" [nzXs]="24" nzHasFeedback>
                            <nz-input [nzSize]="'large'" formControlName="key" [nzId]="'key'"></nz-input>
                            <div nz-form-explain
                                 *ngIf="getFormControl('key').dirty&&getFormControl('key').hasError('key')">请填写正确的标签!
                            </div>
                        </div>
                    </div>

                    <div nz-form-item nz-row>
                        <div nz-form-label nz-col [nzSm]="6" [nzXs]="24">
                            <label for="value" nz-form-item-required>数据值</label>
                        </div>
                        <div nz-form-control nz-col [nzSm]="14" [nzXs]="24" nzHasFeedback>
                            <nz-input [nzSize]="'large'" formControlName="value" [nzId]="'value'"></nz-input>
                            <div nz-form-explain
                                 *ngIf="getFormControl('value').dirty&&getFormControl('value').hasError('value')">
                                请填写正确的数据值!
                            </div>
                        </div>
                    </div>

                    <div nz-form-item nz-row>
                        <div nz-form-label nz-col [nzSm]="6" [nzXs]="24">
                            <label for="descrip">描述</label>
                        </div>
                        <div nz-form-control nz-col [nzSm]="14" [nzXs]="24" nzHasFeedback>
                            <nz-input [nzSize]="'large'" formControlName="descrip" value=""
                                      [nzId]="'descrip'"></nz-input>
                        </div>
                    </div>

                    <div nz-form-item nz-row>
                        <div nz-form-label nz-col [nzSm]="6" [nzXs]="24">
                            <label for="order">排序</label>
                        </div>
                        <div nz-form-control nz-col [nzSm]="14" [nzXs]="24" nzHasFeedback>
                            <nz-input [nzSize]="'large'" formControlName="order" value=""
                                      [nzId]="'order'"></nz-input>
                        </div>
                    </div>
                </form>
            </ng-template>
            <ng-template #modalFooter>
                <button nz-button [nzType]="'default'" [nzSize]="'large'" (click)="handleCancel()">
                    返 回
                </button>
                <button nz-button [nzType]="'primary'" [nzSize]="'large'" (click)="handleOk()"
                        [nzLoading]="isConfirmLoading">
                    提 交
                </button>
            </ng-template>
        </nz-modal>
        <nz-table #nzTable [nzDataSource]="data" [nzPageSize]="10" [nzIsPagination]="false">
            <thead nz-thead>
            <tr>
                <th nz-th [nzWidth]="'20%'"><span>类型</span></th>
                <th nz-th [nzWidth]="'20%'"><span>标签</span></th>
                <th nz-th [nzWidth]="'15%'"><span>数据值</span></th>
                <th nz-th [nzWidth]="'20%'"><span>描述</span></th>
                <th nz-th [nzWidth]="'10%'"><span>排序</span></th>
                <th nz-th><span>操作</span></th>
            </tr>
            </thead>
            <tbody nz-tbody>
            <tr nz-tbody-tr *ngFor="let data of data;let i = index;">
                <td nz-td>
                    <span *ngIf="editRow!==data.id">{{data.type}}</span>
                    <span *ngIf="editRow===data.id">
              <nz-input [(ngModel)]="tempEditObject[data.id].type"></nz-input>
            </span>
                </td>
                <td nz-td>
                    <span *ngIf="editRow!==data.id">{{data.key}}</span>
                    <span *ngIf="editRow===data.id">
              <nz-input [(ngModel)]="tempEditObject[data.id].key"></nz-input>
            </span>
                </td>
                <td nz-td>
                    <span *ngIf="editRow!==data.id">{{data.value}}</span>
                    <span *ngIf="editRow===data.id">
              <nz-input [(ngModel)]="tempEditObject[data.id].value"></nz-input>
            </span>
                </td>
                <td nz-td>
                    <span *ngIf="editRow!==data.id">{{data.descrip}}</span>
                    <span *ngIf="editRow===data.id">
              <nz-input [(ngModel)]="tempEditObject[data.id].descrip"></nz-input>
            </span>
                </td>
                <td nz-td>
                    <span *ngIf="editRow!==data.id">{{data.order}}</span>
                    <span *ngIf="editRow===data.id">
              <nz-input [(ngModel)]="tempEditObject[data.id].order"></nz-input>
            </span>
                </td>
                <td nz-td>   
            <span *ngIf="editRow!==data.id">
              <a (click)="edit(data)">编辑</a>
                <span nz-table-divider></span>
                 <nz-popconfirm [nzTitle]="'确定删除?'" (nzOnConfirm)="delet(data.id,i)">
                     <a nz-popconfirm>删除</a>
                 </nz-popconfirm>
            </span>
                    <span *ngIf="editRow===data.id">
              <a (click)="update(data)">修改</a>
              <span nz-table-divider></span>
                <nz-popconfirm [nzTitle]="'确定取消?'" (nzOnConfirm)="cancel(data)">
                  <a nz-popconfirm>取消</a>
                </nz-popconfirm>
            </span>
                </td>
            </tr>
            </tbody>
        </nz-table>
        <div class="page-container">
            <nz-pagination [(nzPageIndex)]="page.pageNum" [nzTotal]="page.total"
                           [(nzPageSize)]="page.pageSize" (nzPageIndexChange)="getPage(page.pageNum)">
            </nz-pagination>
        </div>`,
    styles: []
})
export class DictListComponent implements OnInit {
    constructor(private router: Router,
                private _message: NzMessageService,
                private http: HttpClient,
                private ref: ChangeDetectorRef,
                private fb: FormBuilder,) {
    }

    _value = '';
    data = [];
    editRow = null;
    tempEditObject = {};
    page: any = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
    };
    isVisible = false;
    isConfirmLoading = false;
    validateForm: FormGroup;

    ngOnInit() {
        this.findAll(1);
        this.validateForm = this.fb.group({
            type: [null, [Validators.required]],
            key: [null, [Validators.required]],
            value: [null, [Validators.required]],
            descrip: [null, []],
            order: [null, []]
        });
    }

    getFormControl(name) {
        return this.validateForm.controls[name];
    }

    showModal = () => {
        this.isVisible = true;
    };

    handleOk(): void {
        for (const i in this.validateForm.controls) {
            this.validateForm.controls[i].markAsDirty();
            if (this.validateForm.controls[i].invalid) return;
        }
        this.isConfirmLoading = true;
        this.http.post(AppUrl.dict.addUrl,
            {
                type: this.validateForm.controls.type.value,
                key: this.validateForm.controls.key.value,
                value: this.validateForm.controls.value.value,
                descrip: this.validateForm.controls.descrip.value,
                order: this.validateForm.controls.order.value
            })
            .subscribe(data => {
                console.log(data);
                this.valueHandler(data);
            }, reject => {
                this.errorHandler(reject);
            });
    }

    handleCancel = (e) => {
        this.isVisible = false;
    };

    valueHandler(data) {
        this.isVisible = false;
        this.isConfirmLoading = false;
        this._message.success('添加成功', {nzDuration: 3000});
        console.log(data);
        let temp: any = data;
        this.page = temp.data;
        this.data = this.page.list;
        this.ref.markForCheck();
        this.ref.detectChanges();
        // this.router.navigate('sys/dict/dict-list');
        // this.router.navigate(['sys/dict/dict-list'],{ replaceUrl: true });
    }

    errorHandler(reject) {
        this._message.success('服务错误', {nzDuration: 3000});
        this.isConfirmLoading = false;
    }

    onSearch(event: string): void {
        console.log(event);
        this.http.post(AppUrl.dict.findUrl,
            {type: this._value, pageNo: 1, pageSize: this.page.pageSize})
            .subscribe(data => {
                console.log(data);
                this._message.success('查询成功', {nzDuration: 3000});
                let temp: any = data;
                this.page = temp.data;
                this.data = this.page.list;
                this.ref.markForCheck();
                this.ref.detectChanges();
            }, reject => {
                this._message.success('服务错误', {nzDuration: 3000});
            });
    }


    edit(data) {

        this.tempEditObject[data.id] = {...data};
        this.editRow = data.id;
    }

    update(data) {
        Object.assign(data, this.tempEditObject[data.id]);
        if (data.type && data.key && data.value) {
            this.http.post(AppUrl.dict.updateUrl,
                {
                    id: data.id,
                    type: data.type,
                    key: data.key,
                    value: data.value,
                    descrip: data.descrip,
                    order: data.order
                })
                .subscribe(data1 => {
                    console.log(data1);
                    Object.assign(data, this.tempEditObject[data.id]);
                    this.editRow = null;
                }, reject => {
                    this._message.success('修改失败', {nzDuration: 3000});
                });
        } else {
            this._message.success('补全字段', {nzDuration: 3000});
        }
    }

    cancel(data) {
        this.tempEditObject[data.id] = {};
        this.editRow = null;
    }

    addDict() {
        this.router.navigate(['/sys/dict/dict-add']);
    }

    delet(id, i) {
        this.http.post(AppUrl.dict.deltUrl, {id: id}).subscribe(data => {
            let temp: any = data;
            if (temp.code == 200) {
                this._message.success('删除成功', {nzDuration: 3000});
                this.data.splice(i, 1);
            }
        });
    }

    findAll(pageNum) {
        this.http.post(AppUrl.dict.findAllUrl, {pageNo: pageNum, pageSize: this.page.pageSize}).subscribe(data => {
            let temp: any = data;
            if (temp.code == 200) {
                this.page = temp.data;
                this.data = this.page.list;
            }
        });
    }


    /**
     * 分页举例-ts部分
     * 声明对象page，初始化pageNum（当前页码），pageSize（每页多少条数据），total（总数据条数，初始化0）
     * 声明方法getPage（pageNum），其中写具体http请求和数据处理
     * 获得的数据中，令this.page = temp.data;分页数据列表存储在this.page.list中
     * */

    getPage(pageNum) {
        if (this._value === '') {
            this.findAll(pageNum);
        }
        else {
            this.http.post(AppUrl.dict.findUrl, {
                type: this._value,
                pageNo: pageNum,
                pageSize: this.page.pageSize
            }).subscribe(data => {
                let temp: any = data;
                if (temp.code == 200) {
                    this.page = temp.data;
                    this.data = this.page.list;
                }
            });
        }

    }
}

